package org.eclipse.emf.cdo.ui.merge.views;


import java.util.ArrayList;

import org.eclipse.emf.cdo.common.branch.CDOBranch;
import org.eclipse.emf.cdo.common.commit.CDOChangeSetData;
import org.eclipse.emf.cdo.common.id.CDOIDAndVersion;
import org.eclipse.emf.cdo.common.model.CDOModelConstants;
import org.eclipse.emf.cdo.common.revision.delta.CDOFeatureDelta;
import org.eclipse.emf.cdo.eresource.CDOResource;
import org.eclipse.emf.cdo.internal.common.revision.CDORevisionImpl;
import org.eclipse.emf.cdo.internal.common.revision.delta.CDORevisionDeltaImpl;
import org.eclipse.emf.cdo.session.CDOSession;
import org.eclipse.emf.cdo.transaction.CDOTransaction;
import org.eclipse.emf.cdo.ui.CDOItemProvider;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EStructuralFeature;
import org.eclipse.emf.spi.cdo.DefaultCDOMerger;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.CheckboxTreeViewer;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerSorter;
import org.eclipse.net4j.util.container.IContainer;
import org.eclipse.net4j.util.container.IPluginContainer;
import org.eclipse.net4j.util.ui.views.ContainerItemProvider;
import org.eclipse.net4j.util.ui.views.IElementFilter;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.ViewPart;


/**
 * This sample class demonstrates how to plug-in a new
 * workbench view. The view shows data obtained from the
 * model. The sample creates a dummy model on the fly,
 * but a real implementation would connect to the model
 * available either in this or another plug-in (e.g. the workspace).
 * The view is connected to the model using a content provider.
 * <p>
 * The view uses a label provider to define how model
 * objects should be presented in the view. Each
 * view can present the same model objects using
 * different labels and icons, if needed. Alternatively,
 * a single label provider can be shared between views
 * in order to ensure that objects of the same type are
 * presented in the same way everywhere.
 * <p>
 */

public class MergeView extends ViewPart {

	/**
	 * The ID of the view as specified by the extension.
	 */
	public static final String ID = "org.eclipse.emf.cdo.ui.merge.views.SampleView";

	private TableViewer viewer;
	
	private Action action1;
	private Action action2;
	private Action doubleClickAction;
	//private CDOChangeSetData result;
	/*
	 * The content provider class is responsible for
	 * providing objects to the view. It can wrap
	 * existing objects in adapters or simply return
	 * objects as-is. These objects may be sensitive
	 * to the current input of the view, or ignore
	 * it and always show the same content 
	 * (like Task List, for example).
	 */
	 
	class ViewContentProvider implements IStructuredContentProvider {
		private CDOChangeSetData result;
		//private Map<CDOID, Conflict> conflicts;
		
		public void inputChanged(Viewer v, Object oldInput, Object newInput) {
		}
		public void dispose() {
		}
		public Object[] getElements(Object parent) {
			
			//TESTDATA
			ContainerItemProvider<IContainer<Object>> abc = createContainerItemProvider();
			CDOSession session = (CDOSession)IPluginContainer.INSTANCE.getElement("org.eclipse.emf.cdo.sessions", "cdo",
	        "tcp://localhost:2036?repositoryName=repo1&automaticPackageRegistry=true");
			CreateTestData(session);
			//return new String[][] {{"One", "Two"}, {"three", "four"} };
			
			/*
			result= new CDOChangeSetDataImpl();
			 
			*/
			ArrayList<Object> retlist = new ArrayList<Object>() ;
			retlist.add("Merges");
			for(CDOIDAndVersion x :result.getNewObjects()){
				retlist.add("New " + x.getID().toString());
				if(x instanceof CDORevisionImpl){
					CDORevisionImpl rev = (CDORevisionImpl) x;
					EStructuralFeature feature = rev.getEClass().getEStructuralFeature(
					        CDOModelConstants.RESOURCE_NODE_NAME_ATTRIBUTE);
					
					retlist.add(x.getID().toString() + rev.toString());
					retlist.add(x.getID().toString()+ rev.getValue(feature).toString());
					//rev.getValue(feature)
				}
			}
			for(CDOIDAndVersion x :result.getChangedObjects()){
				retlist.add("UPDATE " + x.getID().toString());
				if(x instanceof CDORevisionDeltaImpl){
					CDORevisionDeltaImpl rev = (CDORevisionDeltaImpl) x;
					for(CDOFeatureDelta deltas : rev.getFeatureDeltas())
					retlist.add(deltas.toString());
					//rev.getValue(feature)
				}
			}
			for(CDOIDAndVersion x :result.getDetachedObjects()){
				retlist.add(x.getID().toURIFragment());
				if(x instanceof CDORevisionImpl){
					CDORevisionImpl rev = (CDORevisionImpl) x;
					retlist.add(rev.toString());
					//rev.getValue(feature)
				}
			}
			
			/*conflicts =  new HashMap<CDOID, Conflict>();
			retlist.add("Conflicts");
			for (Entry<CDOID, Conflict> entry : conflicts.entrySet())
		    {
				if(entry instanceof ChangedInSourceAndTargetConflict){
					ChangedInSourceAndTargetConflict x = (ChangedInSourceAndTargetConflict) entry;
					retlist.add(x.getID());
		
				}
				else if(entry instanceof ChangedInSourceAndDetachedInTargetConflict){
					ChangedInSourceAndDetachedInTargetConflict x = (ChangedInSourceAndDetachedInTargetConflict) entry;
					retlist.add(x.getID());
				}
				else if(entry instanceof ChangedInTargetAndDetachedInSourceConflict){
					ChangedInTargetAndDetachedInSourceConflict x = (ChangedInTargetAndDetachedInSourceConflict)entry;
					retlist.add(x.getID());
				}
				else{
					//unknown Conflict
				}
				
		    }
				*/
			return retlist.toArray();
		}
		private void CreateTestData(CDOSession session){
			CDOBranch mainBranch = session.getBranchManager().getMainBranch();
		    CDOTransaction transaction = session.openTransaction(mainBranch);

		    //CDOResource resource = transaction.createResource("/testres");
		  //  EList<EObject> contents = resource.getContents();
		    //add 6
		    //long time1 = transaction.commit().getTimeStamp();
		    
		    CDOBranch source1 = mainBranch.getBranch("mergetest1");
		    CDOBranch source2 = mainBranch.getBranch("mergetest2");
		    CDOBranch source3 = mainBranch.getBranch("mergetest3");
		  //  CDOTransaction trans1 = session.openTransaction(source2);
		   // trans1.merge(source1.getHead(), new DefaultCDOMerger.PerFeature.ManyValued());
		    result =  transaction.merge(source3.getHead(), new DefaultCDOMerger.PerFeature.ManyValued());
		    
		    transaction.close();
		   // trans1.close();
		   // transaction.commit();

		  //sleep
		 /*   CDOTransaction tx2 = session.openTransaction(source2);
		    CDOResource res2 = tx2.getResource("/res");
		    EList<EObject> contents2 = res2.getContents();
		  //add 1 
		    tx2.commit();
		    tx2.close();

		    transaction.merge(source2.getHead(), new DefaultCDOMerger.PerFeature.ManyValued());
		    transaction.commit();*/

		   // CDOChangeSetData result = transaction.merge(source2.getHead(), new DefaultCDOMerger.PerFeature.ManyValued());
		    
		}
		protected ContainerItemProvider<IContainer<Object>> createContainerItemProvider()
		  {
		    return new CDOItemProvider(getSite().getPage(), new IElementFilter()
		    {
		      public boolean filter(Object element)
		      {
		        return element instanceof CDOSession;
		      }
		    });
		  }
		
	}
	class ViewLabelProvider extends LabelProvider implements ITableLabelProvider {
		public String getColumnText(Object obj, int index) {
			String text = (String) obj;
			switch (index) {
			case 0:
				return text;
			case 1:	
				return text;
				default:
					return "unknown";
			}
		}
		public Image getColumnImage(Object obj, int index) {
			return getImage(obj);
		}
		public Image getImage(Object obj) {
			return PlatformUI.getWorkbench().
					getSharedImages().getImage(ISharedImages.IMG_OBJ_ELEMENT);
		}
	}
	class NameSorter extends ViewerSorter {
	}

	/**
	 * The constructor.
	 */
	public MergeView() {
	}

	/**
	 * This is a callback that will allow us
	 * to create the viewer and initialize it.
	 */
	public void createPartControl(Composite parent) {
		
		
		viewer = new TableViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
		Table table = viewer.getTable();
		table.setHeaderVisible(true);
		table.setLinesVisible(true);
		
		String[] ColNames = new String[] {"row1","row2"};
		
		for(int i = 0; i< ColNames.length; i++){
			TableColumn tabCol = new TableColumn(table, SWT.LEFT);
			tabCol.setText(ColNames[i]);
			tabCol.setWidth(100);
		}
		viewer.setContentProvider(new ViewContentProvider());
		viewer.setLabelProvider(new ViewLabelProvider());
		viewer.setSorter(new NameSorter());
		viewer.setInput(getViewSite());

		// Create the help context id for the viewer's control
		PlatformUI.getWorkbench().getHelpSystem().setHelp(viewer.getControl(), "org.eclipse.emf.cdo.ui.merge.viewer");
		makeActions();
		hookContextMenu();
		hookDoubleClickAction();
		contributeToActionBars();
	}

	private void hookContextMenu() {
		MenuManager menuMgr = new MenuManager("#PopupMenu");
		menuMgr.setRemoveAllWhenShown(true);
		menuMgr.addMenuListener(new IMenuListener() {
			public void menuAboutToShow(IMenuManager manager) {
				MergeView.this.fillContextMenu(manager);
			}
		});
		Menu menu = menuMgr.createContextMenu(viewer.getControl());
		viewer.getControl().setMenu(menu);
		getSite().registerContextMenu(menuMgr, viewer);
	}

	private void contributeToActionBars() {
		IActionBars bars = getViewSite().getActionBars();
		fillLocalPullDown(bars.getMenuManager());
		fillLocalToolBar(bars.getToolBarManager());
	}

	private void fillLocalPullDown(IMenuManager manager) {
		manager.add(action1);
		manager.add(new Separator());
		manager.add(action2);
	}

	private void fillContextMenu(IMenuManager manager) {
		manager.add(action1);
		manager.add(action2);
		// Other plug-ins can contribute there actions here
		manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
	}
	
	private void fillLocalToolBar(IToolBarManager manager) {
		manager.add(action1);
		manager.add(action2);
	}

	private void makeActions() {
		action1 = new Action() {
			public void run() {
				showMessage("Action 1 executed");
			}
		};
		action1.setText("Action 1");
		action1.setToolTipText("Action 1 tooltip");
		action1.setImageDescriptor(PlatformUI.getWorkbench().getSharedImages().
			getImageDescriptor(ISharedImages.IMG_OBJS_INFO_TSK));
		
		action2 = new Action() {
			public void run() {
				showMessage("Action 2 executed");
			}
		};
		action2.setText("Action 2");
		action2.setToolTipText("Action 2 tooltip");
		action2.setImageDescriptor(PlatformUI.getWorkbench().getSharedImages().
				getImageDescriptor(ISharedImages.IMG_OBJS_INFO_TSK));
		doubleClickAction = new Action() {
			public void run() {
				ISelection selection = viewer.getSelection();
				Object obj = ((IStructuredSelection)selection).getFirstElement();
				showMessage("Double-click detected on "+obj.toString());
			}
		};
	}

	private void hookDoubleClickAction() {
		viewer.addDoubleClickListener(new IDoubleClickListener() {
			public void doubleClick(DoubleClickEvent event) {
				doubleClickAction.run();
			}
		});
	}
	private void showMessage(String message) {
		MessageDialog.openInformation(
			viewer.getControl().getShell(),
			"Sample View",
			message);
	}

	/**
	 * Passing the focus request to the viewer's control.
	 */
	public void setFocus() {
		viewer.getControl().setFocus();
	}
}